import os
import sys

from pathlib import Path

import qdarkstyle
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QPushButton, QHBoxLayout, QApplication, QMessageBox

import LeftTabWidget
import RightWidget

import util
from LeftTabWidget import SheetChooseWidget, TAB_CHOOSE_USE_CHECK
from MainFunc import StartWork
from RightWidget import ChooseDirWidget
from Title import TitleWidget


class MainForm(QWidget):
    def __init__(self):
        super(MainForm, self).__init__()

        self.merge_choose_select = None
        self.right_widget = None
        self.title = None
        self.left_tree_widget = None
        self.btn_start = None
        self.mouse_x = 0
        self.mouse_y = 0
        self.origin_x = 0
        self.origin_y = 0

        self.init_ui()

    def init_ui(self):
        self.hide_title()
        self.title = TitleWidget()

        self.left_tree_widget = SheetChooseWidget()
        self.right_widget = ChooseDirWidget()

        layout = QVBoxLayout()
        layout.addWidget(self.title)
        h_layout = QHBoxLayout()
        h_layout.addWidget(self.left_tree_widget)

        # 开始按钮
        self.btn_start = QPushButton('开始')
        right_v_layout = QVBoxLayout()
        right_v_layout.addWidget(self.right_widget, stretch=1)
        right_v_layout.addWidget(self.btn_start, stretch=1)
        right_v_layout.addStretch(1)
        h_layout.addLayout(right_v_layout)
        layout.addLayout(h_layout)
        desktop = QApplication.desktop()
        self.setFixedSize(int(desktop.width() * 0.6), int(desktop.height() * 0.6))

        self.setLayout(layout)

        self.title.title_signal.connect(self.get_signal_from_title)
        self.right_widget.rootdir_edit.textChanged.connect(
            lambda: self.update_tree_root(self.right_widget.rootdir_edit.text()))
        self.update_tree_root(util.get_config(RightWidget.ROOT_DIR))
        self.btn_start.clicked.connect(self.slot_btn_start)
        self.left_tree_widget.file_list_widget.file_list_edit.textChanged.connect(
            self.right_widget.disable_job_finished_widget)

    def update_tree_root(self, root_path):
        util.my_logger.debug('文件树目录更新:{}'.format(root_path))
        if not root_path:
            root_path = Path.cwd().__str__()
        self.left_tree_widget.update_file_tree_path(Path(root_path))

    def hide_title(self):
        self.setWindowFlags(Qt.FramelessWindowHint)

    def get_signal_from_title(self, num):
        if util.MIN_SIGNAL == num:
            self.showMinimized()
        elif util.MAX_SIGNAL == num:
            self.max_normal()
        else:
            self.close()

    def max_normal(self):
        if self.isMaximized():
            self.showNormal()  # 窗口化显示
        else:
            self.showMaximized()  # 最大化显示

    # 1.鼠标点击事件
    def mousePressEvent(self, evt):
        # 获取鼠标当前的坐标
        self.mouse_x = evt.globalX()
        self.mouse_y = evt.globalY()

        # 获取窗体当前坐标
        self.origin_x = self.x()
        self.origin_y = self.y()

    # 2.鼠标移动事件
    def mouseMoveEvent(self, evt):
        # 计算鼠标移动的x，y位移
        move_x = evt.globalX() - self.mouse_x
        move_y = evt.globalY() - self.mouse_y
        # 计算窗体更新后的坐标：更新后的坐标 = 原本的坐标 + 鼠标的位移
        dest_x = self.origin_x + move_x
        dest_y = self.origin_y + move_y

        # 移动窗体
        self.move(dest_x, dest_y)

    def show_message(self, message):
        util.my_logger.debug(message)
        QMessageBox.information(self, "Warning", message,
                                QMessageBox.Yes)

    @staticmethod
    def get_excel_file_by_dir(parent: Path):
        if not parent.is_dir():
            return
        result = set()
        for i in parent.iterdir():
            if Path(i).suffix == '.xlsx':
                result.add(Path(i).resolve())
        return result

    def slot_btn_start(self):
        file_list = util.get_config(LeftTabWidget.FILE_LIST)
        root_dir = util.get_config(RightWidget.ROOT_DIR)
        tar_dir = util.get_config(RightWidget.TARGET_DIR)
        if file_list:
            util.my_logger.debug(Path(file_list).is_file())
        if root_dir:
            util.my_logger.debug(Path(root_dir).is_dir())
        if tar_dir:
            util.my_logger.debug(Path(tar_dir).is_dir())
        self.merge_choose_select = self.left_tree_widget.get_cur_choose()
        util.my_logger.debug('当前选择', self.left_tree_widget.get_cur_choose())

        # use check choose
        if self.merge_choose_select == TAB_CHOOSE_USE_CHECK:
            dir_list = [i for i, j in self.left_tree_widget.file_check_widget.get_check_files().items() if
                        j and Path(i).is_dir()]
            dir_list += [i for i, j in self.left_tree_widget.file_check_widget.get_check_files().items() if
                         j and Path(i).suffix == '.xlsx']
            excel_list = set()
            for i in dir_list:
                single_dir_excels = self.get_excel_file_by_dir(Path(i))
                if single_dir_excels:
                    excel_list = excel_list | self.get_excel_file_by_dir(Path(i))
                else:
                    # all files are .xlsx
                    excel_list.add(Path(i).resolve())
            if not Path(tar_dir).is_dir() or (0 == len(excel_list)):
                self.show_message('请检查目标文件夹路径/选中的合并文件是否有错')
                return

            self.start_work(None, excel_list, tar_dir)

        else:
            # use file merge
            if not tar_dir or not root_dir or not file_list:
                self.show_message('请检查三个路径是否有空')
                return
            if len(tar_dir) == 0:
                tar_dir = os.path.dirname(file_list)
                self.right_widget.tarfile_edit.setText(tar_dir)
            if not (Path(tar_dir).is_dir() and Path(root_dir).is_dir() and Path(file_list).is_file()):
                self.show_message('请检查三个路径是否有错')
                return

            self.start_work(root_dir, file_list, tar_dir)

    def start_work(self, root_dir, filelist, tar_dir):
        # if self.left_tree_widget.get_cur_choose():
        target_file, not_found_files = StartWork(root_dir, filelist, tar_dir)
        util.my_logger.debug('WorkEnd')
        self.right_widget.generate_file_edit.setText(target_file)
        self.right_widget.show_job_finished_widget()
        if len(not_found_files):
            self.show_message(str(not_found_files) + ' not found!!!!')


if __name__ == "__main__":
    util.log_config()

    app = QApplication(sys.argv)
    mainForm = MainForm()
    mainForm.show()
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    # or in new API
    app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5'))
    sys.exit(app.exec_())
